package org.kingtop.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.kingtop.model.IUserPO;
import org.springframework.beans.factory.annotation.Value;

/**
 * 主要用于生成加密密码，默认使用md5算法
 */
public class PasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    /**
     * 加密方式
     */
    @Value("${password.algorithmName}")
    private String algorithmName = "md5";
    /**
     * 
     */
    @Value("${password.hashIterations}")
    private int hashIterations = 2;

    /**
     * 用于生成随机数列
     * @param randomNumberGenerator
     */
    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    /**
     * 重置密码
     * @param user 用户信息，需要包括用户名和密码
     * <p>将返回重新设置的密码和加密字符salt
     */
    public void encryptPassword(IUserPO user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getUserName() + user.getSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
    
    /**
     * 根据提供的密码和加密字符对密码进行加密
     * @param password 密码
     * @param credentialsSalt 加密字符
     * @return 加密后的密码
     */
    public String encryptPassword(String password, String credentialsSalt){
    	return new SimpleHash(
                algorithmName,
                password,
                ByteSource.Util.bytes(credentialsSalt),
                hashIterations).toHex();
    }
}
